<template>
  <div
    :style="'height: ' + innerHeight + 'px'"
    v-loading="loading"
    element-loading-text="页面正在加载中..."
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :element-loading-lock="true"
  >
    <!--分页组件-->
    <pager
      :tbcols="tbcols"
      :tbdata="tbdata"
      :Pagination="Pagination"
      :reloadPagerData="reloadPagerData"
      ref="tbpager"
    >
      <template #tbColSlot>
        <el-table-column label="设置" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="listRowSelect(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </template>
      <template #serchInner>
        <el-form label-width="120px" :model="editData">
          <el-row :gutter="20">
            <el-col :span="5">
              <el-form-item label="开始日期">
                <span style="padding-right: 10px">>=</span>
                <el-date-picker
                  v-model="serchParam.riqi1"
                  type="date"
                  placeholder="选择日期"
                  style="width: 150px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="结束日期">
                <span style="padding-right: 10px"><=</span>
                <el-date-picker
                  v-model="serchParam.riqi2"
                  type="date"
                  placeholder="选择日期"
                  style="width: 150px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="日期">
                <span style="padding-right: 10px">=</span>
                <el-date-picker
                  v-model="serchParam.riqi3"
                  type="date"
                  placeholder="选择日期"
                  style="width: 150px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: -15px">
            <el-col :span="5">
              <el-form-item label="车牌号">
                <el-input v-model="serchParam.chepaihaoLike" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="车型">
                <el-input v-model="serchParam.chexingLike" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="结算方式">
                <el-select v-model="serchParam.jiesuanfangshi" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in options_jsfs"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="单据分类">
                <el-select v-model="serchParam.nrtype" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in dicData_nrtype"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: -15px">
            <el-col :span="5">
              <el-form-item label="客户名称">
                <el-input v-model="serchParam.kehunameLike" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="单号">
                <el-input v-model="serchParam.danhaoLike" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="备注">
                <el-input v-model="serchParam.beizhuLike" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="结算状态">
                <el-select v-model="serchParam.isjiesuan" placeholder="请选择" size="small">
                  <el-option
                    v-for="item in isjiesuanList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <!--分页控件标题区域-->
      <template #soltTitle> 维修单管理 </template>
      <!--表格操作按钮区域  以具名插槽的方式使用-->
      <template #slotBts>
        <!--
        <el-button type="primary" @click="getSelectRow">选择</el-button>
        <el-button type="info">编辑</el-button>      
        
          <el-button type="success" @click="add">新建</el-button>
          <el-button type="danger" @click="stop">禁用/启用</el-button>
        -->
        <template v-for="(item, index) in buttons" :key="index">
          <template v-if="item.value == 'Search'">
            <el-button
              @click="reloadPagerData"
              :style="'color:#000;background-color:' + item.color + ';'"
              >查询</el-button
            >
          </template>
          <template v-else-if="item.value == 'Audit'">
            <el-button @click="audit" :style="'color:#fff;background-color:#8B0000;'"
              >审核</el-button
            >
          </template>
          <template v-else>
            <el-button
              v-if="!bthide"
              @click="methodUtils(item.value)"
              :style="'color:#fff;background-color:' + item.color + ';'"
              >{{ item.name }}</el-button
            >
          </template>
        </template>
      </template>
    </pager>
    <div
      style="
        background-color: #f1f1f1;
        padding: 20px;
        padding-top: 5px;
        padding-bottom: 5px;
        color: #4f4f4f;
      "
    >
      <span>配件总金额：{{ sumData.pjsum }}</span>
      <span style="margin-left: 30px">维修总金额：{{ sumData.wxsum }}</span>
      <span style="margin-left: 30px">总金额：{{ sumData.zsum }}</span>
    </div>

    <!--弹窗控件-->
    <detail ref="mx" :detailSave="detailSave">
      <template #content>
        <div :style="'height: ' + mxHeight + 'px;overflow-y:auto;overflow-x:hidden;'">
          <div style="background-color: #ccc">
            <el-form label-width="120px" :model="editData">
              <el-row :gutter="5">
                <el-col :span="5">
                  <el-form-item label="日期">
                    {{ editData.riqi }}
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item label="单号">
                    {{ editData.danhao }}
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item
                    label="车牌号"
                    style="display: flex; justify-content: space-between"
                  >
                    <div class="disableInput">{{ editData.car_carno }}</div>
                    <el-button size="small" type="primary" style="width: 80px" @click="carSelect"
                      >选择</el-button
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                 
                </el-col>
              </el-row>

              <el-row :gutter="5" style="margin-top: -20px">
                <el-col :span="5">
                  <el-form-item label="公里数">
                    <el-input v-model="editData.gonglishu" size="small"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label="结算方式">
                    <!--<el-input v-model="editData.jiesuanfangshi" size="small"></el-input>-->
                    <el-select v-model="editData.jiesuanfangshi" placeholder="请选择" size="small">
                      <el-option
                        v-for="item in options_jsfs"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label="单据分类">
                    <el-select v-model="editData.nrtype" placeholder="请选择" size="small">
                      <el-option
                        v-for="item in dicData_nrtype"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>                
                <el-col :span="5">
                  <el-form-item label="备注">
                    <el-input v-model="editData.beizhu" size="small"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="5" style="margin-top: -20px; background-color: aquamarine">
                <el-col :span="20">
                  <el-form-item label="客户/车辆信息">
                    <span style="padding-right: 35px">客户名称：{{ editData.car_kname }}</span>
                    <span style="padding-right: 35px">车牌号：{{ editData.car_carno }}</span>
                    <span style="padding-right: 35px">车型：{{ editData.car_chexing }}</span>
                    <span style="padding-right: 35px">车架号：{{ editData.car_chejiahao }}</span>
                    <span style="padding-right: 35px">保险公司：{{ editData.bxgsName }}</span>
                    <span style="padding-right: 35px"
                      >保险到期日期：{{ editData.car_baoxiandqrq }}</span
                    >
                    <span>电话：{{ editData.car_dianhua }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div :style="'height: ' + (mxHeight - 150) + 'px;overflow-y:auto;overflow-x:hidden;'">
            <el-tabs v-model="activeName">
              <!-- 选项卡1、配件明细 -->
              <el-tab-pane label="配件明细" name="first">
                <div style="height: 40px; background-color: #f1f1f1">
                  <el-button type="primary" @click="addpjbt">新增</el-button>
                  <el-button type="primary" @click="selectPeijian">新增通用类配件</el-button>
                  <el-button type="danger" @click="delpjmx">删除</el-button>
                </div>
                <div>
                  <el-table
                    :data="mxList"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                  >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="pjPid" label="配件编号" width="250"> </el-table-column>
                    <el-table-column prop="pname" label="配件名称" width="250"> </el-table-column>
                    <el-table-column prop="chexing" label="车型" width="180"> </el-table-column>
                    <el-table-column prop="shuliang" label="数量" width="120">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.shuliang"
                          size="small"
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                          @change="txtChange"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="danjia" label="单价" width="120">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.danjia"
                          size="small"
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                          @change="txtChange"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="jine" label="金额" width="120">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.jine"
                          size="small"
                          readonly="readonly"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="beizhu" label="备注">
                      <template #default="scope">
                        <el-input v-model="scope.row.beizhu" size="small"></el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div>配件总金额：{{ pjJine }}</div>
                </div>
              </el-tab-pane>
              <!-- 选项卡2、维修项目明细 -->
              <el-tab-pane label="维修项目明细" name="second">
                <div style="height: 40px; background-color: #f1f1f1">
                  <el-button type="primary" @click="wxmxAddBt">新增</el-button>
                  <el-button type="danger" @click="delpjwx">删除</el-button>
                </div>
                <div>
                  <el-table
                    :data="wxList"
                    style="width: 100%"
                    @selection-change="handleSelectionChange_Wx"
                  >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="weixiuxiangmu" label="维修项目" width="300">
                      <template #default="scope">
                        <el-input v-model="scope.row.weixiuxiangmu" size="small"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="jine" label="费用" width="180">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.jine"
                          size="small"
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="beizhu" label="备注">
                      <template #default="scope">
                        <el-input v-model="scope.row.beizhu" size="small"></el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div>维修总金额：{{ wxzJine }}</div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div style="background-color: #ccc; margin-bottom: 10px">合计总金额：{{ zongJine }}</div>

          <el-dialog title="配件选择" v-model="dialogVisible_Zhanghao" width="80%">
            <div :style="'height: ' + mxHeight + 'px;overflow-y:auto;overflow-x:hidden;'">
              <peijian ref="peijianModel" :bthide="true" :tbSelectbt="tbSelectbt" />
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible_Zhanghao = false">取 消</el-button>
              <el-button type="primary" @click="tbSelect">选 择</el-button>
            </span>
          </el-dialog>

          <el-dialog title="维修项目设置" v-model="dialogVisible_Wxmx" width="500">
            <div style="height: 200px; overflow-y: auto; overflow-x: hidden">
              <el-form label-width="120px" :model="wxmxInput">
                <el-row :gutter="5">
                  <el-col :span="20">
                    <el-form-item label="维修项目">
                      <el-input v-model="wxmxInput.weixiuxiangmu"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="5">
                  <el-col :span="20">
                    <el-form-item label="费用">
                      <el-input
                        v-model="wxmxInput.jine"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible_Wxmx = false">取 消</el-button>
              <el-button type="primary" @click="wxmxSelect">确 认</el-button>
            </span>
          </el-dialog>

          <el-dialog title="配件添加" v-model="dialogVisible_pj2add" width="500">
            <div style="height: 200px; overflow-y: auto; overflow-x: hidden">
              <el-form label-width="120px" :model="pjmxInput">
                <el-row :gutter="5">
                  <el-col :span="20">
                    <el-form-item label="配件编号">
                      <el-input v-model="pjmxInput.mxpjid"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="5">
                  <el-col :span="20">
                    <el-form-item label="配件名称">
                      <el-input v-model="pjmxInput.mxpname"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="5">
                  <el-col :span="20">
                    <el-form-item label="车型">
                      <el-input v-model="pjmxInput.mxchexing"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="5">
                  <el-col :span="20">
                    <el-form-item label="销售价">
                      <el-input
                        v-model="pjmxInput.mxxiaoshoujia"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible_pj2add = false">取 消</el-button>
              <el-button type="primary" @click="pj2addconfirm">确 认</el-button>
            </span>
          </el-dialog>
          <el-dialog title="车辆选择" v-model="dialogVisible_carselect" width="90%">
            <div :style="'height: ' + mxHeight + 'px;overflow-y:auto;overflow-x:hidden;'">
              <car :bthide="true" :cartbSelectbt="cartbSelectbt"></car>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="danger" @click="dialogVisible_carselect = false">关闭</el-button>
            </span>
          </el-dialog>
        </div>
      </template>
    </detail>

    <el-dialog title="单据打印" v-model="dialogVisible_Print" width="65%">
      <div :style="'height: ' + mxHeight + 'px;overflow-y:auto;overflow-x:hidden;'">
        <div id="printTable">
          <div style="text-align: center; font-size: 22px; font-weight: bold">
            夏津中源汽车销售有限公司
          </div>
          <div style="margin-top: 10px">
            <table style="width: 98%; margin: 0 auto">
              <tr>
                <td style="width: 33.33%">
                  单据日期：{{ moment(editData.riqi).format('YYYY-MM-DD') }}
                </td>
                <td style="width: 33.33%">单号：{{ editData.danhao }}</td>
                <td style="width: 33.33%">车牌号：{{ editData.car_carno }}</td>
              </tr>
              <tr>
                <td style="width: 33.33%">客户名称：{{ editData.car_kname }}</td>
                <td style="width: 33.33%">联系电话：{{ editData.car_dianhua }}</td>
                <td style="width: 33.33%">
                  结算方式：{{ editData.jiesuanfangshi == 1 ? '挂账' : '现金' }}
                </td>
              </tr>
              <tr>
                <td style="width: 33.33%">车型：{{ editData.car_chexing }}</td>
                <td style="width: 33.33%">里程数：{{ editData.gonglishu }}</td>
                <td style="width: 33.33%"></td>
              </tr>
            </table>
          </div>
          <div style="margin-top: 10px" v-if="mxList.length > 0">
            配件明细
            <table style="width: 100%; margin: 0 auto" class="fine-line-table">
              <tr style="text-align: center; font-weight: bold">
                <td style="width: 70px">序号</td>
                <td style="width: 90px; text-align: left">配件编号</td>
                <td>配件名称</td>
                <td>车型</td>
                <td style="width: 70px">数量</td>
                <td style="width: 90px">单价</td>
                <td style="width: 90px">金额</td>
              </tr>
              <tr v-for="(item, index) in mxList" :key="index">
                <td style="text-align: center">{{ index + 1 }}</td>
                <td>{{ item.pjPid }}</td>
                <td>{{ item.pname }}</td>
                <td>{{ item.chexing }}</td>
                <td>{{ item.shuliang }}</td>
                <td>{{ item.danjia }}</td>
                <td>{{ item.jine }}</td>
              </tr>
              <tr>
                <td colspan="7">配件合计：{{ editData.peijiansum }}</td>
              </tr>
            </table>
          </div>
          <div style="margin-top: 10px" v-if="wxList.length > 0">
            维修项目
            <table style="width: 100%; margin: 0 auto" class="fine-line-table">
              <tr v-for="(item, index) in wxList" :key="index">
                <td style="width: 70px; text-align: center">{{ index + 1 }}</td>
                <td style="width: 200px">{{ item.weixiuxiangmu }}</td>
                <td>{{ item.jine }}</td>
              </tr>
              <tr>
                <td colspan="3">维修合计：{{ editData.weixiusum }}</td>
              </tr>
            </table>
          </div>
          <div style="text-align: right; margin-right: 50px">总费用：{{ editData.zsum }}</div>
          <div>
            <sapn>夏津中源汽车销售有限公司</sapn>
            <sapn style="padding-left: 40px">电话：0534-2197444</sapn>
          </div>
          <div>救援热线：0534-2197444</div>
          <div>地址：山东省德州市夏津县北城街道苦水社区西侧</div>
          <div>主要经营：大众、奥迪、宝马、奔驰等欧系中高端车型 维修保养</div>
          <div>代办车险、代办车辆年审检测、24小时救援</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-print="'#printTable'">打 印</el-button>
        <el-button @click="dialogVisible_Print = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup name="miyaouser">
import moment from 'moment'
import http from '@/api/http'
import { onMounted, ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import pager from '@/components/zjc/pager.vue'
import detail from '@/components/zjc/details.vue'
import peijian from '@/views/zjcQixiu/peijian.vue'
import car from '@/views/zjcQixiu/car.vue'
import { type Paginations } from '@/model/pagination.ts'
import store from '@/store/index.js'
import { useRoute } from 'vue-router'
import permission from '@/api/zjc/zjcpermission.js'

let isjiesuanList = reactive([
  { value: 0, label: '未结算' },
  { value: 1, label: '已结算' },
  { value: -1, label: '全部' }
])
//字典数据
let dicData_nrtype = reactive([])

const listRowSelect = async (row) => {
  await addOrUpdOpen(row.Id)
}

const sumData = reactive({ pjsum: 0, wxsum: 0, zsum: 0 })
const jintian = new Date()
let firstDay = new Date(jintian.getFullYear(), jintian.getMonth(), 1)

const serchParam = reactive({
  riqi1: firstDay,
  riqi2: null,
  riqi3: null,
  danhaoLike: null,
  chepaihaoLike: null,
  chexingLike: null,
  jiesuanfangshi: null,
  kehunameLike: null,
  beizhuLike: null,
  isjiesuan: 0,
  nrtype: null
})
const dialogVisible_Print = ref(false)
const dialogVisible_Zhanghao = ref(false)
const peijianModel = ref(null)
//=====================【选择数据模块】===============================//
//公共调用方法，在多选和单选之后的共同操作
const sameSelectMethed = () => {
  //重新计算每列金额
  txtChange()
  peijianModel.value.clearSelectRow()
  dialogVisible_Zhanghao.value = false
}
//这是商品页面 》 商品列表页面点击【选择】按钮时调用的、这里是单选
const tbSelectbt = (x) => {
  //alert(JSON.stringify(x));
  var rowItem = {
    Id: '00000000-0000-0000-0000-000000000000',
    pid: x.Id,
    pname: x.pname,
    chexing: x.chexing,
    pjPid: x.pid,
    shuliang: 1,
    danjia: x.xiaoshoujia,
    jine: 0,
    beizhu: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    nrId: '00000000-0000-0000-0000-000000000000'
  }
  mxList.push(rowItem)
  sameSelectMethed()
}
//这是明细页面 》 调用选中行，这里是多选

const tbSelect = () => {
  var selectRow = peijianModel.value.getSelectRow()
  //alert(JSON.stringify(selectRow));
  if (selectRow.length == 0) {
    return
  }

  let selectData = selectRow.map((x) => {
    return {
      Id: '00000000-0000-0000-0000-000000000000',
      pid: x.Id,
      pname: x.pname,
      chexing: x.chexing,
      pjPid: x.pid,
      shuliang: 1,
      danjia: x.xiaoshoujia,
      jine: 0,
      beizhu: null,
      CreateID: null,
      Creator: null,
      CreateDate: null,
      ModifyID: null,
      Modifier: null,
      ModifyDate: null,
      nrId: '00000000-0000-0000-0000-000000000000',
      mxpname: null,
      mxchexing: null,
      mxpjid: null,
      notselectdata: 0
    }
  })

  selectData.forEach((x) => {
    mxList.push(x)
  })
  sameSelectMethed()
}

//=====================【选择数据模块】结束===============================//

//配件明细添加
let dialogVisible_pj2add = ref(false)
let pjmxInput = reactive({ mxpname: null, mxchexing: null, mxpjid: null, mxxiaoshoujia: null })
const addpjbt = () => {
  dialogVisible_pj2add.value = true
}
const pj2addconfirm = () => {
  if (pjmxInput.mxpname == null) {
    ElMessage({
      message: '配件名称不能为空！',
      type: 'error'
    })
    return
  }
  let item = {
    Id: '00000000-0000-0000-0000-000000000000',
    pid: null,
    pname: pjmxInput.mxpname,
    chexing: pjmxInput.mxchexing,
    pjPid: pjmxInput.mxpjid,
    shuliang: 1,
    danjia: pjmxInput.mxxiaoshoujia,
    jine: pjmxInput.mxxiaoshoujia == null ? 0 : pjmxInput.mxxiaoshoujia,
    beizhu: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    nrId: '00000000-0000-0000-0000-000000000000',
    mxpname: pjmxInput.mxpname,
    mxchexing: pjmxInput.mxchexing,
    mxpjid: pjmxInput.mxpjid,
    notselectdata: 1
  }
  mxList.push(item)
  pjmxInput.mxpname = null
  pjmxInput.mxchexing = null
  pjmxInput.mxpjid = null
  pjmxInput.mxxiaoshoujia = null
  dialogVisible_pj2add.value = false
}

const selectPeijian = () => {
  dialogVisible_Zhanghao.value = true
}

const options_jsfs = reactive([
  { label: '现金', value: 0 },
  { label: '挂账', value: 1 }
])

//选项卡默认选择项
const activeName = ref('first')

//明细表格选中行数据
const mxList = reactive([])

const selectedRows = ref([])
const delpjmx = () => {
  let newData = mxList.filter((row) => !selectedRows.value.includes(row))
  mxList.splice(0)
  newData.forEach((item) => mxList.push(item))
  selectedRows.value = [] // 清空选中行数组
}
const handleSelectionChange = (val) => {
  selectedRows.value = val
}
//明细删除选中行逻辑结束

//维修明细表格选中行数据
const wxList = reactive([])
const selectedRows_wx = ref([])
const delpjwx = () => {
  let newData = wxList.filter((row) => !selectedRows_wx.value.includes(row))
  wxList.splice(0)
  newData.forEach((item) => wxList.push(item))
  selectedRows_wx.value = [] // 清空选中行数组
}
const handleSelectionChange_Wx = (val) => {
  selectedRows_wx.value = val
}
//维修明细删除选中行逻辑结束

const txtChange = () => {
  for (var i = 0; i < mxList.length; i++) {
    mxList[i].jine = mxList[i].shuliang * mxList[i].danjia
  }
}

//配件总金额
const pjJine = computed<Number>({
  // 读取值
  get() {
    let zjine = 0
    for (var i = 0; i < mxList.length; i++) {
      if (mxList[i].jine != null) {
        zjine = zjine + parseFloat(mxList[i].jine)
      }
    }
    return zjine
  },
  // 写入值
  set(newVal) {
    console.log(newVal) // 李-四
    //[firstName.value, lastName.value] = newVal.split('-') // 解构赋值
  }
})

//维修总金额
const wxzJine = computed<Number>({
  // 读取值
  get() {
    let zjine = 0
    for (var i = 0; i < wxList.length; i++) {
      if (wxList[i].jine != null) {
        zjine = zjine + parseFloat(wxList[i].jine)
      }
    }
    return zjine
  },
  // 写入值
  set(newVal) {
    console.log(newVal) // 李-四
    //[firstName.value, lastName.value] = newVal.split('-') // 解构赋值
  }
})

const zongJine = computed<Number>({
  // 读取值
  get() {
    let zjine = 0
    for (var i = 0; i < mxList.length; i++) {
      if (mxList[i].jine != null) {
        zjine = zjine + parseFloat(mxList[i].jine)
      }
    }
    for (var i = 0; i < wxList.length; i++) {
      if (wxList[i].jine != null) {
        zjine = zjine + parseFloat(wxList[i].jine)
      }
    }
    return zjine
  },
  // 写入值
  set(newVal) {
    console.log(newVal) // 李-四
    //[firstName.value, lastName.value] = newVal.split('-') // 解构赋值
  }
})

const buttons = reactive([])
const mx = ref()
const tbpager = ref(null)
const editData = reactive({})

const loading = ref(false)
const innerHeight = ref(window.innerHeight - 140)

const mxHeight = ref(innerHeight.value * 0.7)

//定义分页参数
let Pagination: Paginations = reactive({
  Sort: 'CreateDate',
  SortType: ' desc ',
  PageIndex: 1,
  PageSize: 10,
  TotalCount: 0
})
//定义表格列的信息
let tbcols: any[] = [
  { prop: 'riqi', label: '时间', width: 180, align: 'center' },
  { prop: 'danhao', label: '单号', width: 120, align: 'left' },
  { prop: 'car_carno', label: '车牌号', width: 120, align: 'center' },
  { prop: 'car_chexing', label: '车型', width: 180, align: 'center' },
  { prop: 'car_kname', label: '客户名称', width: 180, align: 'center' },
  { prop: 'jiesuanfangshiValue', label: '结算方式', width: 120, align: 'center' },
  { prop: 'bxgsName', label: '保险公司', width: 180, align: 'center' },
  { prop: 'zsum', label: '总费用', width: 180, align: 'left' },
  { prop: 'isjiesuanValue', label: '结算状态', width: 180, align: 'left' },
  { prop: 'beizhu', label: '备注', width: null, align: 'left' }
]
//定义表格数据
let tbdata: any[] = reactive([])

//获取选中行
/**
 * vue3 语法糖的方法中没法直接使用this.$refs
 * 解决方案：定义一个变量，并且变量的名字和要获取数据的子组件的ref的名字一致
 * 然后使用变量名.value.子组件中的方法名或变量名 即可调用子组件中的数据。
 * 注意子组件中调用的数据需要对外暴漏：defineExpose({dataonLineListSelections});
 */
const getSelectRow = () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  alert(JSON.stringify(selectRowsData))
}

//重新执行分页
const reloadPagerData = async (Pagination: Paginations) => {
  loading.value = true
  await loadData().then((res) => {
    tbdata.splice(0, tbdata.length)
    tbdata.push(...res)
    dicData_nrtype.splice(0, dicData_nrtype.length)
    for (var i = 0; i < res.dicD[0].data.length; i++) {
      dicData_nrtype.push(res.dicD[0].data[i])
    }
    dicData_nrtype.push({ key: null, value: '未设置' })
    //alert(JSON.stringify(res.dicD));

    loading.value = false
  })
}

async function loadData() {
  //第一步：加载分页数据
  const arr = await loadPagerData()

  //第二步：追加分页数据属性
  var i = 0
  for (i = 0; i < arr.length; i++) {
    var item = arr[i]
    item.car_baoxiandqrq =
      item.car_baoxiandqrq == null
        ? null
        : moment.utc(item.car_baoxiandqrq).local().format('YYYY-MM-DD')
    Object.assign(arr[i], {
      jiesuanfangshiValue: item.jiesuanfangshi == 0 ? '现金' : '挂账',
      isjiesuanValue: item.isjiesuan == 1 ? '已结算' : '未结算'
      //UserName: await GetColValueByKey('sys_user', 'UserName', 'User_Id', item.UserId)
    })
  }

  //第三步：加载合计费用
  await loadSumData()

  //第四步：加载字典数据
  const res = await loadDicData()
  Object.assign(arr, { dicD: res })
  return arr
}

const loadDicData = async () => {
  const res = await http.post('api/Sys_Dictionary/GetVueDictionary', ['wxdtype'], true)
  return res
}

async function loadSumData() {
  if (serchParam.riqi1 != null) {
    serchParam.riqi1 = moment.utc(serchParam.riqi1).local().format('YYYY-MM-DD')
  }
  if (serchParam.riqi2 != null) {
    serchParam.riqi2 = moment.utc(serchParam.riqi2).local().format('YYYY-MM-DD')
  }
  if (serchParam.riqi3 != null) {
    serchParam.riqi3 = moment.utc(serchParam.riqi3).local().format('YYYY-MM-DD')
  }
  const arr = []
  const res = await http.get('api/qx_wxd_nr/GetSumJineJson', {}, false, {
    params: Object.assign(serchParam, Pagination)
  })
  if (res.Tag == 1) {
    //alert(JSON.stringify(res.Data));
    sumData.pjsum = res.Data[0]
    sumData.wxsum = res.Data[1]
    sumData.zsum = res.Data[2]
  } else {
    ElMessage({
      message: '系统异常，操作失败！',
      type: 'error'
    })
  }
  return arr
}

async function loadPagerData() {
  if (serchParam.riqi1 != null) {
    serchParam.riqi1 = moment.utc(serchParam.riqi1).local().format('YYYY-MM-DD')
  }
  if (serchParam.riqi2 != null) {
    serchParam.riqi2 = moment.utc(serchParam.riqi2).local().format('YYYY-MM-DD')
  }
  if (serchParam.riqi3 != null) {
    serchParam.riqi3 = moment.utc(serchParam.riqi3).local().format('YYYY-MM-DD')
  }
  const arr = []
  const res = await http.get('api/qx_wxd_nr/GetPageDataZjc', {}, false, {
    params: Object.assign(serchParam, Pagination)
  })
  if (res.Tag == 1) {
    //alert(JSON.stringify(res.Data));
    arr.push(...res.Data)
    Pagination.TotalCount = res.Total
  } else {
    ElMessage({
      message: '系统异常，操作失败！',
      type: 'error'
    })
  }
  return arr
}

async function GetColValueByKey(
  tableName: string,
  selectColName: string,
  whereKey: string,
  whereKeyValue: string
) {
  /**
   * 这里注意 第三个参数一定要设置为false
   * 设置为false即关闭loading动画加载效果
   * 设置它为false就会避免页面在加载的时候不断的闪烁
   */
  const result = await http.get('api/sys/GetColValueByKey', {}, false, {
    params: {
      tableName: tableName,
      selectColName: selectColName,
      whereKey: whereKey,
      whereKeyValue: whereKeyValue
    }
  })
  return result
}

//增删改查方法综合调度
const methodUtils = async (category) => {
  //alert(category)
  if (category == 'Add') {
    await addOrUpdOpen('00000000-0000-0000-0000-000000000000')
  } else if (category == 'DisableUse') {
    stop()
  } else if (category == 'Delete') {
    del()
  } else if (category == 'Update') {
    let selectRowsData = tbpager.value.dataonLineListSelections
    if (selectRowsData.length != 1) {
      ElMessage({
        message: '只能选择至少1行数据！',
        type: 'error'
      })
      return
    }
    await addOrUpdOpen(selectRowsData[0].Id)
  } else if (category == 'Print') {
    let selectRowsData = tbpager.value.dataonLineListSelections
    if (selectRowsData.length != 1) {
      ElMessage({
        message: '只能选择至少1行数据！',
        type: 'error'
      })
      return
    }

    execPrint(selectRowsData[0].Id)
  }
}

//======维修明细模块处理=======//
const dialogVisible_Wxmx = ref(false)
const wxmxInput = reactive({
  weixiuxiangmu: null,
  jine: null
})
//弹出框确认
const wxmxSelect = () => {
  if (wxmxInput.weixiuxiangmu == null) {
    ElMessage({
      message: '操作失败，维修项目不能为空！',
      type: 'error'
    })
    return
  }
  const item = {
    Id: '00000000-0000-0000-0000-000000000000',
    weixiuxiangmu: wxmxInput.weixiuxiangmu,
    jine: wxmxInput.jine,
    beizhu: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    nrId: null
  }

  wxList.push(item)

  dialogVisible_Wxmx.value = false
  //alert(JSON.stringify(wxmxInput))
}
//维修明细“新增”按钮点击
const wxmxAddBt = () => {
  wxmxInput.weixiuxiangmu = null
  wxmxInput.jine = null
  dialogVisible_Wxmx.value = true
}
//======维修明细模块处理结束=======//

//打印
const execPrint = async (id) => {
  mxList.splice(0)
  wxList.splice(0)
  await loadDjData(id).then((x) => {
    dialogVisible_Print.value = true
  })
}
//添加或修改信息
const addOrUpdOpen = async (id) => {
  mxList.splice(0)
  wxList.splice(0)
  await loadDjData(id).then((x) => {
    let title_a = '修改维修单信息'

    //新增初始化
    if (editData.Id == '00000000-0000-0000-0000-000000000000') {
      title_a = '添加维修单信息'
    } else {
    }
    mx.value.loadPage(title_a, '90%')
    //alert(JSON.stringify(editData));
  })
}
const loadDjData = async (id) => {
  await http.get('api/qx_wxd_nr/GetObjectJson', {}, false, { params: { Id: id } }).then((res) => {
    Object.assign(editData, res.Data)
    editData.car_baoxiandqrq =
      editData.car_baoxiandqrq == null
        ? null
        : moment.utc(editData.car_baoxiandqrq).local().format('YYYY-MM-DD')
    //alert(JSON.stringify(editData));
  })

  //加载配件明细
  await http
    .get('api/qx_mx_peijian/GetList', {}, false, {
      params: { nrId: id }
    })
    .then((res) => {
      //alert(JSON.stringify(res))
      if (res.Tag == 1) {
        for (var i = 0; i < res.Data.length; i++) {
          mxList.push(res.Data[i])
        }
      } else {
        alert('服务器错误，数据加载失败！')
      }
    })

  //加载维修项目明细
  await http
    .get('api/qx_mx_weixiu/GetList', {}, false, {
      params: { nrId: id }
    })
    .then((res) => {
      //alert(JSON.stringify(res))
      if (res.Tag == 1) {
        for (var i = 0; i < res.Data.length; i++) {
          wxList.push(res.Data[i])
        }
      } else {
        alert('服务器错误，数据加载失败！')
      }
    })
}

//用户删除
const del = async () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  if (selectRowsData.length != 1) {
    ElMessage({
      message: '只能选择至少1行数据！',
      type: 'error'
    })
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 删除操作
    const res = await http.get('api/qx_wxd_nr/DeleteFrom2Json', {}, true, {
      params: {
        id: selectRowsData[0].Id
      }
    })

    if (res.Tag == 1) {
      ElMessage({
        message: '数据删除成功!',
        type: 'success'
      })
      await reloadPagerData(Pagination)
    } else {
      ElMessage({
        message: '系统错误，操作失败！',
        type: 'error'
      })
    }
  } catch (err) {
    // 用户取消了删除
    //console.log('取消了删除');
  }
}

//禁用与开启
const stop = async () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  if (selectRowsData.length != 1) {
    ElMessage({
      message: '只能选择至少1行数据！',
      type: 'error'
    })
    return
  }

  const res = await http.get('api/miyaouser/StopFormJson', {}, true, {
    params: {
      Miyao_Id: selectRowsData[0].Miyao_Id
    }
  })

  if (res.Tag == 1) {
    ElMessage({
      message: '操作成功，该用户已被禁用或启用!',
      type: 'success'
    })
    await reloadPagerData(Pagination)
  } else {
    ElMessage({
      message: '系统错误，操作失败！',
      type: 'error'
    })
  }
}

//明细保存
const detailSave = async () => {
  if (editData.jiesuanfangshi == null) {
    editData.jiesuanfangshi = 0
  }
  editData.peijiansum = pjJine
  editData.weixiusum = wxzJine
  editData.zsum = zongJine
  //alert(JSON.stringify(editData));
  const res = await http.post(
    'api/qx_wxd_nr/SaveFormJson',
    { nr: editData, list_peijian: mxList, list_weixiu: wxList },
    true
  )
  if (res.Tag == 1) {
    ElMessage({
      message: '操作成功！',
      type: 'success'
    })
    mx.value.dialogVisible = false
    await reloadPagerData(Pagination)
  } else {
    ElMessage({
      message: res.Message,
      type: 'error'
    })
  }
}

//页面初始化加载完成钩子
onMounted(async () => {
  //获取当前页面路由
  const route = useRoute()
  //alert(route.path);
  //获取缓存中的权限信息
  let store_permission = store.getters.getPermission(route.path)
  //alert(JSON.stringify(store_permission));
  //在权限信息中获取按钮
  var permissionButtons = permission.getButtons(route.path)
  if (permissionButtons) {
    //2020.03.31添加深拷贝按钮组
    permissionButtons.forEach((p) => {
      let _obj = {}
      for (const key in p) {
        _obj[key] = p[key]
      }
      buttons.push(_obj)
    })
    // this.buttons.push(...permissionButtons);
  }
  //alert(JSON.stringify(buttons))

  await reloadPagerData(Pagination)
})

//===========车辆选择模块开始============//
let dialogVisible_carselect = ref(false)
const carSelect = () => {
  dialogVisible_carselect.value = true
}
const cartbSelectbt = (obj) => {
  //alert(JSON.stringify(obj));
  editData.carId = obj.Id
  editData.notselectdataCar = 1
  editData.car_carno = obj.carno
  editData.car_kname = obj.kname
  editData.car_dianhua = obj.dianhua
  editData.car_chexing = obj.chexing
  editData.car_chejiahao = obj.chejiahao
  dialogVisible_carselect.value = false
}
//===========车辆选择模块结束============//

const audit = async () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  if (selectRowsData.length != 1) {
    ElMessage({
      message: '只能选择至少1行数据！',
      type: 'error'
    })
    return
  }
  const res = await http.get('api/qx_wxd_nr/AuditFormJson', {}, true, {
    params: {
      Id: selectRowsData[0].Id
    }
  })

  if (res.Tag == 1) {
    ElMessage({
      message: res.Message,
      type: 'success'
    })
    await reloadPagerData(Pagination)
  } else {
    ElMessage({
      message: '系统错误，操作失败！',
      type: 'error'
    })
  }
}
</script>

<style scoped>
.fine-line-table {
  border-collapse: collapse;
  width: 100%;
}

.fine-line-table,
.fine-line-table th,
.fine-line-table td {
  border: 1px solid #ddd;
}
.disableInput {
  border: 1px solid #2d2d2d;
  width: calc(100% - 85px);
  height: 30px;
  line-height: 30px;
  margin-right: 5px;
  background-color: #e5e5e5;
}
</style>
